package com.wennn.top.shop.biz.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wennn.top.common.enums.OrderEnum;
import com.wennn.top.common.util.BeanUtils;
import com.wennn.top.common.vo.IResult;
import com.wennn.top.core.exception.WBusiException;
import com.wennn.top.security.util.ContextUtil;
import com.wennn.top.shop.biz.coupon.service.IYxStoreCouponService;
import com.wennn.top.shop.biz.order.entity.YxStoreCart;
import com.wennn.top.shop.biz.order.entity.YxStoreOrder;
import com.wennn.top.shop.biz.order.mapper.YxStoreOrderMapper;
import com.wennn.top.shop.biz.order.service.IYxStoreCartService;
import com.wennn.top.shop.biz.order.service.IYxStoreOrderService;
import com.wennn.top.shop.biz.product.entity.YxStoreProduct;
import com.wennn.top.shop.biz.product.service.IYxStoreProductService;
import com.wennn.top.shop.biz.system.service.IYxSystemStoreService;
import com.wennn.top.shop.biz.user.entity.YxUserAddress;
import com.wennn.top.shop.biz.user.service.IYxUserAddressService;
import com.wennn.top.util.DateUtil;
import com.wennn.top.util.OrderUtils;
import com.wennn.top.web.order.dto.OrderCreateDto;
import com.wennn.top.web.order.vo.ConfirmOrderVo;
import com.wennn.top.web.product.vo.CartInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author wennn
 * @since 2020-05-14
 */
@Service
public class YxStoreOrderServiceImpl extends ServiceImpl<YxStoreOrderMapper, YxStoreOrder> implements IYxStoreOrderService {

    @Autowired
    IYxStoreCartService cartService;

    @Autowired
    IYxUserAddressService addressService;

    @Autowired
    IYxStoreProductService iYxStoreProductService;

    @Autowired
    IYxSystemStoreService iYxSystemStoreService;

    @Autowired
    IYxStoreCouponService iYxStoreCouponService;

    /**
     * 生成订单信息 产生唯一orderKey 在内存或redis中产生
     *
     * @param cartIds
     * @return
     */
    @Override
    public ConfirmOrderVo confirm(String[] cartIds) {
        // 获取有效的购物车
        List<YxStoreCart> carts = cartService.getCarts(cartIds);
        if(carts.isEmpty()){
            throw new WBusiException("购物车信息失效");
        }

        // 数据库订单记录 避免遍历查询
        Map<Integer,YxStoreProduct> dbProduct = iYxStoreProductService.getProduct(carts.parallelStream().map(i -> i.getProductId()).collect(Collectors.toList()));
        List<CartInfoVo> cartInfoVos = carts.parallelStream().map(cart -> {
            CartInfoVo vo = BeanUtils.copy(cart, CartInfoVo.class);
            if (dbProduct.containsKey(cart.getProductId())) {
                vo.setProduct(dbProduct.get(cart.getProductId()));
            }
            return vo;
        }).collect(Collectors.toList());


        // 生成结果
        ConfirmOrderVo result = ConfirmOrderVo.builder()
                // 地址信息 默认地址
                .setAddress(addressService.getDefaultAddr())
                // 购物车信息
                .setCartInfos(cartInfoVos)
                // 优惠券
                .setCoupons(iYxStoreCouponService.getUserCoupons())
                // 用户信息
                .setUserInfo(ContextUtil.getUser())
                // 门店信息
                .setSysStoreInfo("")
                // 其他信息 比如金额 支付信息
                .addParam("priceGroup","");

        return result;
    }


    /**
     * 创建订单，提交订单信息
     * @param vo
     * @param dto
     * @return
     */
    @Override
    public IResult createOrder(ConfirmOrderVo vo, OrderCreateDto dto) {

        YxStoreOrder order = new YxStoreOrder();

        order.setOrderId(OrderUtils.getOrderCode());
        order.setAddTime(DateUtil.nowIntTime());
//        order.setBackIntegral();
        order.setBargainId(-1);
//        order.setCartId()
        order.setUnique(vo.getOrderKey());
        order.setCombinationId(-1);
        order.setCouponId(dto.getCouponId());
        order.setMark(dto.getMark());
        order.setStoreId(dto.getStoreId());
        order.setStatus(OrderEnum.STATUS_0.getValue());
        order.setPayType(dto.getPayType());
        order.setRealName(dto.getRealName());
        order.setUserPhone(dto.getPhone());
        order.setPinkId(-1);
        order.setUid(ContextUtil.getUid());
        YxUserAddress address = addressService.getById(dto.getAddressId());
        order.setUserAddress(address.getDetail());
        int ret = getBaseMapper().insert(order);
        if(ret != 1){
            throw new WBusiException("订单提交失败");
        }
        return IResult.ok(order.getOrderId());
    }


    /**
     * 获取各状态订单数量
     * @param status
     * @param uid
     * @return
     */
    @Override
    public List<Map<String, Integer>> statusCount(String status, String uid) {
        return getBaseMapper().countStatus(status,uid);
    }
}